''' 
测试界面
@Author: Morpheus_on_Earth
@Date: 2023-09-03
'''
import binascii
import os
import numpy as np
import time
import cv2
import datetime
from serial import Serial
from PyQt5 import QtGui
from PyQt5.QtWidgets import QApplication, QListView, QMessageBox, QDesktopWidget, QMainWindow, QDialog, QComboBox, QVBoxLayout, QPushButton, QLabel, QFileDialog
from PyQt5.QtCore import QObject, QTimer
from PyQt5.QtGui import QIcon
from PyQt5.QtSerialPort import QSerialPort, QSerialPortInfo
from PyQt5.QtNetwork import QHostAddress
from styles import Warning_Set
import pyqtgraph as pg
pen1=pg.mkPen(color='#391d00', width=2)
# 指令帧
cmd_force = '01 03 00 50 00 02 C4 1A'
cmd_zero = '01 10 00 5E 00 01 02 00 01 6A EE'
class TestWindow(QObject):
    def __init__(self, parent):
        super(TestWindow, self).__init__()
        # 重要变量
        self.ui = parent.ui
        self.parent = parent

        # 更新串口列表的定时器
        # self.SerialTimer = QTimer()
        # self.SerialTimer.timeout.connect(self.on_comboBox_COM_Activated)
        # self.SerialTimer.start(1000)
        self.ui.pushButton_COM_refresh.clicked.connect(self.on_comboBox_COM_Activated)
        # 界面初始化
        self.InitUI()
        self.ForceTest = ForceTest(self.ui)  # 测试界面-力传感器
        self.DistanceTest = DistanceTest(self.ui)  # 测试界面-距离传感器
        self.CamerTest = CamerTest(self.ui)  # 测试界面-摄像头
        self.SerialHelper = SerialHelper(self.ui)  # 串口助手界面

    def InitUI(self):
        self.ui.tabWidget_3.setCurrentIndex(0)  # 默认显示第一个界面
        # 这样下拉框选项间距可以设置变大
        self.ui.comboBox_COM_ForceSensor.setView(QListView())
        self.ui.comboBox_COM_mcu.setView(QListView())
        self.ui.comboBox_COM_SerialHelper.setView(QListView())  
        self.ui.comboBox_Baud.setView(QListView())
        self.ui.comboBox_Data.setView(QListView())
        self.ui.comboBox_Check.setView(QListView())
        self.ui.comboBox_Stop.setView(QListView())
        self.ui.comboBox_Encoding.setView(QListView())
        self.ui.comboBox_sendCommand.setView(QListView())
        # 设置下拉框默认选项
        self.ui.comboBox_Baud.addItems(["波特率: " + i for i in ["9600", "19200", "38400", "57600", "115200", "自定义波特率"]])
        self.ui.comboBox_Data.addItems(["数据位: " + i for i in ["8", "7", "6", "5"]])
        self.ui.comboBox_Check.addItems(["校验位: " + i for i in ["None", "Even", "Odd", "Mark", "Space"]])
        self.ui.comboBox_Stop.addItems(["停止位: " + i for i in ["1", "1.5", "2", "0"]])
        self.ui.comboBox_Encoding.addItems(["编码方式: " + i for i in ["UTF-8", "GB2312", "GBK", "GB18030", "Big5", "Unicode", "ASCII"]])
        self.ui.comboBox_sendCommand.addItems(["获取力学数据", "归零"])

    def get_port_list(self):
        ''' 获取串口列表 '''
        available_ports = QSerialPortInfo.availablePorts()
        ports = []
        for port in available_ports:
            ports.append(port.portName())
        self.port_list = ports

    def on_comboBox_COM_Activated(self):
        ''' 串口号下拉框激活 '''
        self.ui.comboBox_COM_ForceSensor.clear()
        self.get_port_list()
        self.ui.comboBox_COM_ForceSensor.addItems(self.port_list)
        self.ui.comboBox_COM_mcu.addItems(self.port_list)
        self.ui.comboBox_COM_SerialHelper.addItems(self.port_list)

class ForceTest(QObject):
    def __init__(self, ui):
        super(ForceTest, self).__init__()
        # 重要变量
        self.ui = ui
        self.interval = 200  # 采样间隔(ms)
        self.interval_num = 100  # 一个窗口里的数据点总数
        self.data_force = np.zeros(self.interval_num)  # 力传感器曲线数据
        self.ForceSerial = QSerialPort()  # 力传感器串口对象
        self.mcuSerial = QSerialPort()  # MCU串口对象
        self.timer = QTimer()  # 定时器
        self.timer.timeout.connect(self.on_pushButton_ForceSensor_UpdatePlot)
        self.plot_data_1 = self.ui.PlotWidget_ForceSensor_curve.plot(pen=pen1)
        # 信号与槽函数的连接
        self.ui.pushButton_ForceSensor_connect.clicked.connect(self.on_ForceSensor_connectClicked)  # 力传感器串口连接
        
        self.ui.pushButton_ForceSensor_zero.clicked.connect(self.on_pushButton_ForceSensor_zeroClicked)  # 去皮归零
        self.ui.pushButton_ForceSensor_draw.clicked.connect(self.on_pushButton_ForceSensor_drawClicked)  # 绘制曲线
    
    def on_ForceSensor_connectClicked(self):
        ''' 力传感器串口连接 '''
        if self.ui.pushButton_ForceSensor_connect.text() == "连接":
            self.ForceSerial.setPortName(self.ui.comboBox_COM_ForceSensor.currentText())
            self.ForceSerial.setBaudRate(QSerialPort.Baud9600)
            self.ForceSerial.setDataBits(QSerialPort.Data8)
            self.ForceSerial.setParity(QSerialPort.NoParity)
            self.ForceSerial.setStopBits(QSerialPort.OneStop)
            if self.ForceSerial.open(QSerialPort.ReadWrite) == True:
                print("【测试】力传感器串口打开成功")
            else:
                Warning_Set("力传感器串口打开失败")
                print("【测试】力传感器串口打开失败")
            self.ui.pushButton_ForceSensor_connect.setText("断开")
        else:
            self.ForceSerial.close()
            print("【测试】力传感器串口关闭成功")
            self.ui.pushButton_ForceSensor_connect.setText("连接")
    

    def on_pushButton_ForceSensor_zeroClicked(self):
        ''' 去皮归零 '''
        if self.ForceSerial.isOpen() == True:
            self.ForceSerial.write(bytes.fromhex(cmd_zero))
            print("【测试】去皮归零成功")
        else:
            Warning_Set("力传感器串口未打开")
    
    def on_pushButton_ForceSensor_drawClicked(self):
        ''' 绘制曲线 '''
        if self.ForceSerial.isOpen() == True:
            self.ui.pushButton_ForceSensor_draw.setText("暂停")
            self.ui.pushButton_ForceSensor_draw.clicked.disconnect(self.on_pushButton_ForceSensor_drawClicked)
            self.ui.pushButton_ForceSensor_draw.clicked.connect(self.on_pushButton_ForceSensor_drawPuase)

            self.timer.start(self.interval)  # 定时器间隔200ms采样
        else:
            Warning_Set("力传感器串口未打开")
    
    def on_pushButton_ForceSensor_drawPuase(self):
        ''' 暂停绘制曲线 '''
        self.ui.pushButton_ForceSensor_draw.setText("绘制曲线")
        self.ui.pushButton_ForceSensor_draw.clicked.disconnect(self.on_pushButton_ForceSensor_drawPuase)
        self.ui.pushButton_ForceSensor_draw.clicked.connect(self.on_pushButton_ForceSensor_drawClicked)

    def read_force(self):
        ''' 读取力传感器数据 '''
        if self.ForceSerial.isOpen() == True:
            # 发送命令
            self.ForceSerial.write(bytes.fromhex(cmd_force))
            # 读取数据
            available_bytes = self.ForceSerial.bytesAvailable()
            while available_bytes < 9:
                available_bytes = self.ForceSerial.bytesAvailable()
            return_data = bytes(self.ForceSerial.readAll())
            return_data_hex = str(return_data.hex())
            # print('接收到的信息 ', return_data_hex)

            if return_data_hex[6:10] == 'FFFF' or return_data_hex[6:10] == 'ffff':
                force = int(return_data_hex[10:14], 16)
                force = force-65535
            elif return_data_hex[6:10] == '0000':
                force = int(return_data_hex[10:14], 16)
            return force
        
        else:
            Warning_Set("力传感器串口未打开")
    
    def on_pushButton_ForceSensor_UpdatePlot(self):
        ''' 更新力传感器曲线 '''
        force = self.read_force()
        self.data_force = np.insert(self.data_force, 0, force)  # 将数据放入数组
        self.data_force = self.data_force[:-1]  # 删除最后一个数据
        # print(self.data_force)
        # 绘图
        self.plot_data_1.setData(self.data_force, pen=pen1)

class DistanceTest(QObject):
    def __init__(self, ui):
        super(DistanceTest, self).__init__()
        # 重要变量
        self.ui = ui
        # 信号与槽函数的连接
        self.ui.pushButton_mcu_connect.clicked.connect(self.on_mcu_connectClicked)  # MCU串口连接
        self.ui.pushButton_mcu_connect.clicked.connect(self.update_distance)  # 更新当前位置
        self.ui.pushButton_mcu_connect.clicked.connect(self.update_num)  # 更新通过光电门的次数
    
    def on_mcu_connectClicked(self):
        ''' MCU串口连接 '''
        if self.ui.pushButton_mcu_connect.text() == "连接":
            self.mcuSerial.setPortName(self.ui.comboBox_COM_mcu.currentText())
            self.mcuSerial.setBaudRate(QSerialPort.Baud115200)
            self.mcuSerial.setDataBits(QSerialPort.Data8)
            self.mcuSerial.setParity(QSerialPort.NoParity)
            self.mcuSerial.setStopBits(QSerialPort.OneStop)
            if self.mcuSerial.open(QSerialPort.ReadWrite) == True:
                print("【测试】MCU串口打开成功")
            else:
                Warning_Set("MCU串口打开失败")
                print("【测试】MCU串口打开失败")
            self.ui.pushButton_mcu_connect.setText("断开")
        else:
            self.mcuSerial.close()
            print("【测试】MCU串口关闭成功")
            self.ui.pushButton_mcu_connect.setText("连接")
    
    def update_distance(self):
        ''' 更新当前位置 '''
        pass

    def update_num(self):
        ''' 更新通过光电门的次数 '''
        pass

class CamerTest(QObject):
    def __init__(self, ui):
        super(CamerTest, self).__init__()
        # 重要变量
        self.ui = ui
        # 信号与槽函数的连接
        self.ui.pushButton_camera1_show.clicked.connect(self.on_pushButton_camera1_showClicked)
        self.ui.pushButton_camera1_blink.clicked.connect(self.on_pushButton_camera1_blinkClicked)
        self.ui.pushButton_camera1_takePhoto.clicked.connect(self.on_pushButton_camera1_takePhotoClicked)
        self.ui.pushButton_camera2_show.clicked.connect(self.on_pushButton_camera2_showClicked)
        self.ui.pushButton_camera2_takePhoto.clicked.connect(self.on_pushButton_camera2_takePhotoClicked)

        # 初始化摄像头
        self.COLOR_FACTOR = np.load("./Resources/factor.npy")  #相机颜色校正因子
        self.CAM_NUM_1 = 1  # Supereyes摄像头
        self.CAM_NUM_2 = 2  # HAYEAR自动对焦相机
        self.LED_SEQ = ["L0", "L1", "L8", "L7", "L6", "L5", "L4", "L3", "L2"]  # LED序列
        self.cap_1 = cv2.VideoCapture(self.CAM_NUM_1)
        self.cap_2 = cv2.VideoCapture(self.CAM_NUM_2)
        self.timer_camera_1 = QTimer()
        self.timer_camera_1.timeout.connect(self.show_camera_1)
        self.timer_camera_2 = QTimer()
        self.timer_camera_2.timeout.connect(self.show_camera_2)
        # 连接光圈, 若想直接运行UI可以先注释掉这两行
        # self.light_ctrl = Serial("COM7", 9600)
        # self.light_ctrl.write("L0".encode())  # 关掉所有灯

    def show_camera_1(self):
        ''' 显示Supereyes图像 '''
        flag, self.image_1 = self.cap_1.read()

        self.image_1 = (self.image_1 * self.COLOR_FACTOR).astype(np.float32)     #色彩校正
        self.image_1 = np.clip(self.image_1, 0, 255).astype(np.uint8)
        
        show = cv2.resize(self.image_1, (640, 480))  # 调整图像大小
        show = cv2.cvtColor(show, cv2.COLOR_BGR2RGB)
        showImage = QtGui.QImage(show.data, show.shape[1], show.shape[0], QtGui.QImage.Format_RGB888)
        self.ui.label_camera1_img.setPixmap(QtGui.QPixmap.fromImage(showImage))

    def on_pushButton_camera1_showClicked(self):
        ''' 显示Supereyes摄像头 '''
        if self.ui.pushButton_camera1_show.text() == "成像":
            self.timer_camera_1.start(30)  # 30ms刷新一次
            self.ui.pushButton_camera1_show.setText("停止")
        else:
            self.timer_camera_1.stop()
            self.ui.pushButton_camera1_show.setText("成像")
    
    def on_pushButton_camera1_blinkClicked(self):
        ''' Supereyes光圈闪烁 '''
        for light_num in self.LED_SEQ:
            self.light_ctrl.write(light_num.encode())
            time.sleep(0.5)

    def on_pushButton_camera1_takePhotoClicked(self):
        ''' Supereyes拍照 '''
        for light_num in range(0, 9):
            self.light_ctrl.write(self.LED_SEQ[light_num].encode())
            time.sleep(0.5)

            flag, self.image = self.cap.read()
            # 保存图片
            timestamp = datetime.datetime.now()
            time = timestamp.strftime("%Y-%m-%d-%H-%M-%S")
            img_name = time + '.jpg'
            img_path = os.path.join('./proj/Test/', img_name)
            cv2.imwrite(img_path, self.image)

    
    def show_camera_2(self):
        ''' 显示自动对焦相机图像 '''
        flag, self.image_2 = self.cap_2.read()

        # self.image_2 = (self.image_2 * self.COLOR_FACTOR).astype(np.float32)     #色彩校正
        # self.image_2 = np.clip(self.image_2, 0, 255).astype(np.uint8)


        # show = cv2.resize(self.image_2, (640, 480))  # 调整图像大小
        show = self.image_2
        show = cv2.cvtColor(show, cv2.COLOR_BGR2RGB)
        showImage = QtGui.QImage(show.data, show.shape[1], show.shape[0], QtGui.QImage.Format_RGB888)
        self.ui.label_camera2_img.setPixmap(QtGui.QPixmap.fromImage(showImage))

    def on_pushButton_camera2_showClicked(self):
        ''' 显示自动对焦相机摄像头 '''
        if self.ui.pushButton_camera2_show.text() == "成像":
            self.timer_camera_2.start(30)  # 30ms刷新一次
            self.ui.pushButton_camera2_show.setText("停止")
        else:
            self.timer_camera_2.stop()
            self.ui.pushButton_camera2_show.setText("成像")
    
    def on_pushButton_camera2_takePhotoClicked(self):
        ''' 自动对焦相机拍照 '''
        flag, self.image = self.cap_2.read()
        # 保存图片
        timestamp = datetime.datetime.now()
        time = timestamp.strftime("%Y-%m-%d-%H-%M-%S")
        img_name = time + '.jpg'
        img_path = os.path.join('./proj/Test/', img_name)
        cv2.imwrite(img_path, self.image)

class SerialHelper(QObject):
    def __init__(self, ui):
        # 重要变量
        self.ui = ui
        self.Serial = QSerialPort()  # 串口对象
        self.state = 0  # 串口是否打开: 0-关闭, 1-打开
        self.receive_flag = 0  # 0 ASCII 1 HEX
        self.send_flag = 0  # 0 ASCII 1 HEX
        self.hex_format = 0  # hex格式 0 无空格 1 有空格
        self.port_list = []  # 串口列表
        self.parameters = {}  # 串口参数
        self.ForceMode = 0  # 匹配力传感模式
        # self.received_data  = ''# 接收到的数据
        # 信号与槽函数的连接
        self.ui.pushButton_openCOM.clicked.connect(self.on_pushButton_openCOMClicked)  # 串口打开按键
        self.Serial.readyRead.connect(self.Data_Receive)  # 串口接收数据
        self.ui.pushButton_send.clicked.connect(self.Data_Send)  # 串口数据发送按键
        self.ui.pushButton_receive_form.clicked.connect(self.on_pushButton_receive_formClicked)  # 接收格式按键
        self.ui.pushButton_send_form.clicked.connect(self.on_pushButton_send_formClicked)  # 发送格式按键
        self.ui.pushButton_arange.clicked.connect(self.on_pushButton_arangeClicked)  # HEX数据整理按键
        self.ui.pushButton_clear_receive.clicked.connect(self.ui.textEdit_receive.clear)  # 清空接收区按键
        self.ui.pushButton_clear_send.clicked.connect(self.ui.textEdit_send.clear)  # 清空发送区按键
        self.ui.comboBox_sendCommand.activated.connect(self.FulfillCmd)  # 补全命令
        self.ui.pushButton_ForceMode.clicked.connect(self.on_pushButton_ForceModeClicked)  # 力传感模式


    def on_pushButton_openCOMClicked(self):
        ''' 打开或关闭串口 '''
        # 获取串口参数
        self.parameters['Port'] = self.ui.comboBox_COM_SerialHelper.currentText()
        self.parameters['Baud'] = self.ui.comboBox_Baud.currentText()[5:]
        self.parameters['Data'] = self.ui.comboBox_Data.currentText()[5:]
        self.parameters['Check'] = self.ui.comboBox_Check.currentText()[5:]
        self.parameters['Stop'] = self.ui.comboBox_Stop.currentText()[5:]
        self.parameters['Encoding'] = self.ui.comboBox_Encoding.currentText()[6:]
        # 打开或关闭串口
        if self.state == 0:  # 串口关闭->打开
            # 设置串口号
            self.Serial.setPortName(self.parameters['Port'])
            # 设置波特率(不知道应不应该用内置类型)
            if self.parameters['Baud'] == '9600':
                self.Serial.setBaudRate(QSerialPort.Baud9600)
            elif self.parameters['Baud'] == '19200':
                self.Serial.setBaudRate(QSerialPort.Baud19200)
            elif self.parameters['Baud'] == '38400':
                self.Serial.setBaudRate(QSerialPort.Baud38400)
            elif self.parameters['Baud'] == '57600':
                self.Serial.setBaudRate(QSerialPort.Baud57600)
            elif self.parameters['Baud'] == '115200':
                self.Serial.setBaudRate(QSerialPort.Baud115200)
            # 设置停止位
            if self.parameters['Stop'] == '1':
                self.Serial.setStopBits(QSerialPort.OneStop)
            elif self.parameters['Stop'] == '1.5':
                self.Serial.setStopBits(QSerialPort.OneAndHalfStop)
            elif self.parameters['Stop'] == '2':
                self.Serial.setStopBits(QSerialPort.TwoStop)
            # 设置数据位
            if self.parameters['Data'] == '8':
                self.Serial.setDataBits(QSerialPort.Data8)
            elif self.parameters['Data'] == '7':
                self.Serial.setDataBits(QSerialPort.Data7)
            elif self.parameters['Data'] == '6':
                self.Serial.setDataBits(QSerialPort.Data6)
            elif self.parameters['Data'] == '5':
                self.Serial.setDataBits(QSerialPort.Data5)
            # 设置校验位
            if self.parameters['Check'] == 'None':
                self.Serial.setParity(QSerialPort.NoParity)
            elif self.parameters['Check'] == 'Even':
                self.Serial.setParity(QSerialPort.EvenParity)
            elif self.parameters['Check'] == 'Odd':
                self.Serial.setParity(QSerialPort.OddParity)
            elif self.parameters['Check'] == 'Mark':
                self.Serial.setParity(QSerialPort.MarkParity)
            elif self.parameters['Check'] == 'Space':
                self.Serial.setParity(QSerialPort.SpaceParity)
            # 打开串口
            if self.Serial.open(QSerialPort.ReadWrite) == True:
                self.state = 1
                self.timer.stop()  # 停止定时器
                self.ui.pushButton_openCOM.setIcon(QIcon(":/icons/icon/Resources/icons/off.png"))
                self.ui.pushButton_openCOM.setStyleSheet("QPushButton {border: 2px solid #f87272; border-radius: 25px;}"
                                                  "QPushButton:hover {background-color: #f87272;}")
                print("串口打开成功")
            else:
                self.parent.Warning_Set("串口打开失败")
                print("串口打开失败")
        else:  # 串口打开->关闭
            self.Serial.close()
            self.state = 0
            self.timer.start(1000)  # 启动定时器
            self.ui.pushButton_openCOM.setIcon(QIcon(":/icons/icon/Resources/icons/接口_128x128.png"))
            self.ui.pushButton_openCOM.setStyleSheet("QPushButton {border: 2px solid #858b97; border-radius: 15px;}")
            print("串口关闭成功")

    def on_pushButton_receive_formClicked(self):
        ''' 接收区切换ASCII或HEX显示 '''
        if self.receive_flag == 0:
            self.receive_flag = 1
            self.ui.pushButton_receive_form.setText("接收: HEX")
            self.ui.pushButton_receive_form.setStyleSheet("border-color: #2d94cd;\n color: #2d94cd;")
        else:
            self.receive_flag = 0
            self.ui.pushButton_receive_form.setText("接收: ASCII")
            self.ui.pushButton_receive_form.setStyleSheet("border-color: #fbbc26;\n color: #fbbc26;")
    
    def on_pushButton_send_formClicked(self):
        ''' 发送区切换ASCII或HEX显示 '''
        if self.send_flag == 0:
            self.ui.pushButton_arange.setEnabled(True)
            self.send_flag = 1
            self.ui.pushButton_send_form.setText("发送: HEX")
            self.ui.pushButton_send_form.setStyleSheet("border-color: #2d94cd;\n color: #2d94cd;")
            hex_data = ' '.join(['%02X' % b for b in bytes(self.ui.textEdit_send.toPlainText(), encoding=self.parameters['Encoding'])])
            self.ui.textEdit_send.setText(hex_data)
        else:
            self.ui.pushButton_arange.setEnabled(False)
            self.send_flag = 0
            self.ui.pushButton_send_form.setText("发送: ASCII")
            self.ui.pushButton_send_form.setStyleSheet("border-color: #fbbc26;\n color: #fbbc26;")
            hex_data = self.ui.textEdit_send.toPlainText()
            while ' ' in hex_data:
                hex_data = hex_data.replace(' ', '')
            try:  # 判断HEX是否合法
                binary_data = binascii.unhexlify(hex_data)
                binary_data.decode(self.parameters['Encoding'])
            except:
                self.parent.Warning_Set("HEX格式错误")
                self.send_flag = 1
                self.ui.pushButton_send_form.setText("发送: HEX")
                self.ui.pushButton_send_form.setStyleSheet("border-color: #2d94cd;\n color: #2d94cd;")
                return
            self.ui.textEdit_send.setText(bytes.fromhex(hex_data).decode(self.parameters['Encoding']))
    
    def on_pushButton_arangeClicked(self):
        ''' 发送HEX数据整理 '''
        if self.hex_format == 0:
            self.hex_format = 1
            hex_data= self.ui.textEdit_send.toPlainText()
            # 去掉HEX字符串中的空格
            hex_str = hex_data.replace(' ', '')
            # 将HEX字符串按照每两个字符分割成一个列表
            hex_list = [hex_str[i:i + 2] for i in range(0, len(hex_str), 2)]
            # 将分割后的列表中的元素用分隔符连接起来
            hex_str = ' '.join(hex_list)
            self.ui.textEdit_send.setText(hex_str)
        else:
            self.hex_format = 0
            hex_data = self.ui.textEdit_send.toPlainText()
            # 去掉HEX字符串中的空格
            hex_str = hex_data.replace(' ', '')
            self.ui.textEdit_send.setText(hex_str)

    def Data_Receive(self):
        ''' 串口接收数据 '''
        if self.ForceMode == 1:  # 力传感模式
            # 延时0.1秒, 等待数据接收完毕
            # time.sleep(0.1)
            # bytes(2进制)转换为hex(16进制)
            available_bytes = self.Serial.bytesAvailable()
            if available_bytes >= 9:
                return_data = bytes(self.Serial.readAll())
                return_data_hex = str(return_data.hex())
                return_data_hex_format = ' '.join([return_data_hex[i:i+2] for i in range(0, len(return_data_hex), 2)])            
                self.ui.textEdit_receive.append("返回的数据："+return_data_hex_format)
                if return_data_hex[6:10] == 'ffff':
                    force = int(return_data_hex[10:14], 16)
                    force = force-65535
                    self.ui.textEdit_receive.append("拉力："+str(force)+'g')
                    return force
                elif return_data_hex[6:10] == '0000':
                    force = int(return_data_hex[10:14], 16)
                    self.ui.textEdit_receive.append("压力："+str(force)+'g')
                    return force
            else:
                pass
        else:
            bytes_data = bytes(self.Serial.readAll())  # 二进制数据
            if self.receive_flag == 0:  # ASCII显示(字符串显示)
                self.ui.textEdit_receive.append(bytes_data.decode(self.parameters['Encoding']))
            else:  # HEX显示
                hex_data = ' '.join(['%02X' % b for b in bytes_data])  # %02X 表示将整数转换成两位十六进制数
                self.ui.textEdit_receive.append(hex_data)

    def Data_Send(self):
        ''' 串口发送数据 '''
        data = self.ui.textEdit_send.toPlainText()
        if self.Serial.isOpen() == True:
            if self.send_flag == 0:  # ASCII发送
                self.Serial.write(data.encode(self.parameters['Encoding']))
            else:  # HEX发送
                hex_data = data
                while ' ' in hex_data:
                    hex_data = hex_data.replace(' ', '')
                try:  # 判断HEX是否合法
                    binary_data = binascii.unhexlify(hex_data)
                    # binary_data.decode(self.parameters['Encoding'])
                except:
                    self.parent.Warning_Set("HEX格式错误")
                    return
                self.Serial.write(bytes.fromhex(hex_data))
        else:
            self.parent.Warning_Set("串口未打开")

    def FulfillCmd(self, index):
        # 转换为HEX发送
        self.ui.pushButton_arange.setEnabled(True)
        self.send_flag = 1
        self.ui.pushButton_send_form.setText("发送: HEX")
        self.ui.pushButton_send_form.setStyleSheet("border-color: #2d94cd;\n color: #2d94cd;")
        
        # 指令帧
        cmd_force = '01 03 00 50 00 02 C4 1A'
        cmd_zero = '01 10 00 5E 00 01 02 00 01 6A EE'
        if index == 0:  # 获取力学数据
            self.ui.textEdit_send.setText(cmd_force)
        elif index == 1:  # 归零
            self.ui.textEdit_send.setText(cmd_zero)

    def on_pushButton_ForceModeClicked(self):
        if self.ForceMode == 0:
            self.ForceMode = 1
            self.ui.pushButton_ForceMode.setText("力传感模式\n开")
            self.ui.pushButton_ForceMode.setStyleSheet('border: 2px solid #fbbc26;\nborder-radius: 15px;\nbackground-color: #fbbc26;\ncolor: #ffffff;\nfont:  20px "黑体";')
            if self.receive_flag == 1:  # HEX显示
                self.ui.pushButton_receive_form.setText("接收: ASCII")
                self.ui.pushButton_receive_form.setStyleSheet("border-color: #fbbc26;\n color: #fbbc26;")
                self.receive_flag = 0
        else:
            self.ForceMode = 0
            self.ui.pushButton_ForceMode.setText("力传感模式\n关")
            self.ui.pushButton_ForceMode.setStyleSheet('border: 2px solid #fbbc26;\nborder-radius: 15px;\ncolor: #fbbc26;\nfont:  20px "黑体";')
